
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var select_product_url = $('.select_product_url').val();
    var get_session_pro = $('.get_session_pro').val();
    var edit_purchase_car_url = $('.edit_purchase_car').val();
    var save_purchase_url = $('.save_purchase').val();
    var detail_url = $('.detail_url').val();
    var delete_purchase_car_url = $('.delete_purchase_car_url').val();



    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        toolbar: '#toolbarDemo01',
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        initSort: {
            field: 'create_date' // 排序字段，对应 cols 设定的各字段名
            ,type: 'desc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:true},
            {field: 'id', title: '采购单号', align:"center"},
            {field: 'create_date', title: '创建时间',align:'center',sort: true},
            {field: 'SupplierName', title: '供货商', align:'center'},
            {field: 'total_num', title: '采购总量',width:120, align:'center'},
            {field: 'total_price', title: '采购总金额(￥)', align:'center'},
            {field: 'UserName', title: '创建人', align:'center'},
            {field: 'status', title: '状态', width:80,align:'center', templet:function(data){
                if (data.status == 1) {
                    return '<span class="layui-btn layui-btn-blue layui-btn-xs">待进货</span>'
                } else if(data.status == 2) {
                    return '<span class="layui-btn layui-btn-green layui-btn-xs">已进货</span>'
                }else {
                    return '<span class="layui-btn layui-btn-orange layui-btn-xs">已作废</span>'
                }
            }},
            {field: 'remarks', title: '备注', align:'center',templet:function(data){
                if (data.remarks != null && data.remarks != '') {
                    return data.remarks;
                }else{
                    return '----------';
                }
            }},

            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail" href="/admin/purchase/detail/id/'+ data.id+'"><i class="layui-icon"></i>详情</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon"></i>作废</a>';

                return html;
            }}
        ]]
    });

    // Table 列表
    var detailsTable = table.render({
        elem: '#dataTable100',
        url : detail_url,
        page : false,
        totalRow: true,
        toolbar: '#toolbarDemo',
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        // initSort: {
        //     field: 'create_date' // 排序字段，对应 cols 设定的各字段名
        //     ,type: 'desc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        // },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,totalRowText: '合计'},
            {field: 'product_name', title: '商品名称', width:240},
            {field: 'bar_code', title: '条码', minWidth:240},
            {field: 'spec', title: '规格', minWidth:80},
            {field: 'pu_stock', title: '采购数量', align:'center'},
            {field: 'unit', title: '单位', align:'center'},
            {field: 'purchase_price', title: '进货价', align:'center'},
            {field: 'total_price', title: '总价', align:'center',totalRow: true},


            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/

        ]]
    });
    // Table 列表
    var sessionProduct = table.render({
        elem: '#dataTable02',
        url : get_session_pro,
        page : false,
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        // initSort: {
        //     field: 'create_date' // 排序字段，对应 cols 设定的各字段名
        //     ,type: 'desc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        // },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:true},
            {field: 'name', title: '商品名称', width:240},
            {field: 'img_url', title: '封面图', minWidth:80, align:"center", templet:function(data){
                return '<a href="'+data.img_url+'" target="_blank"><img src="'+data.img_url+'" style="width: 80px;" /></a>';
            }},
            {field: 'bar_code', title: '条码', minWidth:180},
            {field: 'store_count', title: '现有库存', minWidth:80,align:"center"},
            {field: 'caigou_num', title: '采购数量（可编辑）', minWidth:80,align:"center",edit:true},
            {field: 'purchase_price', title: '进货价（可编辑）', minWidth:80, align:"center",edit:true, templet:function(data){
                return '￥' + data.purchase_price
            }},
            {field: 'total', title: '金额（元）', minWidth:80, align:"center", templet:function(data){
                return '￥' + formatMoney(data.purchase_price * data.caigou_num,1)
            }},
            {field: 'unit', title: '单位', align:'center',templet:function(data){
                return show_product_unit(data.unit);
            }},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                return html;
            }}
        ]],
        done: function(res, curr, count){
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            $('#allprice').text(res.allprice)
        }
    });

    table.on('edit(dataTable02_filter)',function (e) {
        //编辑表格单元格
        var field = e.field
        if(field == 'caigou_num'){
            if(!checkRate(e.value)){
                sessionProduct.reload();
                layer.msg('采购数量必须是正整数')
                return false;
            }
        }else {
            if(!checkMoney(e.value)){
                sessionProduct.reload();
                layer.msg('进价不合法')
                return false;
            }
        }
        var value = e.value //得到修改后的值
            ,data = e.data //得到所在行所有键值
        $.ajax({
            url: edit_purchase_car_url,
            data: {"id": data.id,"value":value,"field":field,'product_id':data.product_id},
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 1) {
                    if(field == 'caigou_num'){
                        layer.msg(data.name+ ' 的采购数量修改为 ' + value, {icon: 1});
                    }else {
                        layer.msg(data.name+ ' 的进价修改为 ' + value + '元', {icon: 1});
                    }

                    sessionProduct.reload();
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });



    })

    // 搜索
    $(".search_btn").on("click", function(){
        if($('.name').val() != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $('.searchBox').find('input[name=name]').val()  //搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });


    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });

    $('.add_btn').on('click', function(){

        layer.open({
             type: 1
            , anim: 1
            , title: '选择供应商'
            ,btn: ['确定']
            , closeBtn: 1
            , shade: 0.2
            , shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe'
            , area: ['600px','400px']
            , content: $('#supspr')
            ,yes: function(index, layero){
                var supid = $('#supsprselect').val();
                if(supid == 0){
                    layer.msg('请选择供货商');
                }else {
                    layer.close(index);
                    window.location.href = '/admin/purchase/add/supid/' + supid
                }
                //按钮【按钮一】的回调
            }
        });
        $(".layui-layer-shade").css("display","none");
        //其中：layero是弹层的DOM对象
        // $('#view-modal').modal('toggle');

    });


    $('.save_btn').on('click',function () {
        layer.confirm('是否提交？', {icon: 1, title: '提示信息'}, function (index) {
            var checkStatus = table.checkStatus('tableList');
            var data = checkStatus.data;
            var temp = [];
            if(data.length > 0){
                for (var i = 0;i<data.length;i++) {
                    var datas = {
                        id: data[i].id,
                        name:data[i].name,
                        purchase_price:parseInt(data[i].purchase_price * 100),
                        bar_code:data[i].bar_code,
                        caigou_num:data[i].caigou_num,
                        total_price:parseInt(data[i].purchase_price * 100) * data[i].caigou_num,
                        unit:data[i].unit,
                        spec:data[i].spec,
                        supid:data[i].supid,
                        purchase_id:data[i].purchase_id,
                        product_id:data[i].product_id
                    };
                    temp.push(datas)
                }
                var data = JSON.stringify(temp)
                var remarks =  '';
                if($('#remarks').val().trim() != ''){
                    remarks = $('#remarks').val();
                }
                $.ajax({
                    url: save_purchase_url,
                    data: {data,"remarks":remarks},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg(res.msg);
                            window.location.href = res.url
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            }else {
                layer.msg("请搜索并选择商品");
            }
        })
    });


    $('.search_product').on('click', function(){
        var supid = $('.search_product').data('supid');
        layer.open({
            type: 2
            , anim: 1
            , title: '选择商品'
            , shade: 0.2
            , skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe'
            , area: ['900px','700px']
            , content: select_product_url + '?supid=' + supid,
            end:function () {
                sessionProduct.reload();
            }

        });
    });



    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // 列表操作
    table.on('tool(dataTable02_filter)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_purchase_car_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            sessionProduct.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.2
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
        });
    }



    // 文件上传
    upload.render({
        elem: '.linkLogo',
        url: '../../json/linkLogo.json',
        method : "post",
        done: function(res, index, upload){
            var num = parseInt(4*Math.random());  //生成0-4的随机数，随机显示一个头像信息
            $('.linkLogoImg').attr('src',res.data[num].src);
            $('.linkLogo').css("background","#fff");
        }
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

    })

});